package cn.iocoder.yudao.module.esim.service.esasset;

import cn.iocoder.yudao.module.esim.framework.config.ESimBusinessConfig;
import cn.iocoder.yudao.module.trade.api.order.TradeOrderApi;
import cn.iocoder.yudao.module.trade.api.order.dto.TradeOrderItemRespDTO;
import cn.iocoder.yudao.module.trade.api.order.dto.TradeOrderRespDTO;
import cn.iocoder.yudao.module.trade.enums.order.TradeOrderDeliveryStatusEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Author: li
 * Date: 2024/3/8
 */
@Service
public class ESimOrderApiProxy {
    @Resource
    private TradeOrderApi orderApi;
    @Resource
    private ESimBusinessConfig eSimBusinessConfig;

    public TradeOrderRespDTO getOrderByNo(String no) {
        final boolean mockOrder = eSimBusinessConfig.getMockOrder();
        if (mockOrder) {
            return mockGetOrderByNo(no);
        }

        return orderApi.getOrderByNo(no);
    }

    public void deliveryOrderByNo(String orderNo, boolean success, String reason) {
        final boolean mockOrder = eSimBusinessConfig.getMockOrder();
        if (mockOrder) {
            mockDeliveryOrderByNo(orderNo, success, reason);
            return;
        }

        orderApi.deliveryOrderByNo(orderNo, null, null, success, reason);
    }

    /**********************mock**********************/

    private final Map<String, OrderInfo> orderMap = new HashMap();

    private TradeOrderRespDTO mockGetOrderByNo(String orderNo) {
        final OrderInfo orderInfo = orderMap.get(orderNo);

        final TradeOrderRespDTO order = new TradeOrderRespDTO();
        if (orderInfo != null) {
            if (orderInfo.isSuccess()) {
                order.setDeliveryStatus(TradeOrderDeliveryStatusEnum.DELIVER_SUCCESS.getStatus());
            } else {
                order.setDeliveryStatus(TradeOrderDeliveryStatusEnum.DELIVER_FAILED.getStatus());
            }
        } else {
            order.setDeliveryStatus(TradeOrderDeliveryStatusEnum.UN_DELIVERED.getStatus());
        }

        order.setNo(orderNo);
        order.setPayStatus(true);
        order.setUserId(1L);
        order.setPaymentPrice(1000 * 100);
        order.setOrderCurrency("USD");
        TradeOrderItemRespDTO item = new TradeOrderItemRespDTO();
        item.setSkuId(1648L);
        order.setItems(Arrays.asList(item));
        return order;
    }

    private void mockDeliveryOrderByNo(String orderNo, boolean success, String reason) {
        orderMap.put(orderNo, new OrderInfo(success, reason));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class OrderInfo {
        private boolean success;
        private String reason;
    }

}
